package com.winning.common.xmlSchema.schema;

import com.sun.org.apache.xerces.internal.dom.DOMInputImpl;
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSResourceResolver;

import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * 类名称：SchemaURIResolver
 * 类描述：解决转换过程中默认用于解析xsl文件中document()、xsl:import 或 xsl:include 中所使用的 URI 的对象
 * 创建人：liuwensheng
 * 创建时间：2017-1-12 上午11:10:54
 * 修改人：liuwensheng
 * 修改时间：2017-1-12 上午11:10:54
 * 修改备注：
 */
public class SchemaURIResolver implements LSResourceResolver {

    private static final Map<String, String> NSFILEMAP = new HashMap<String, String>();

    static {
        NSFILEMAP.put("PCHIS_CDA.xsd", "sdschemas/PCHIS_CDA.xsd");
        NSFILEMAP.put("PCHIS_Extension.xsd", "sdschemas/PCHIS_Extension.xsd");
        NSFILEMAP.put("PCHIS_POCD_MT000040.xsd", "sdschemas/PCHIS_POCD_MT000040.xsd");
        NSFILEMAP.put("datatypes.xsd", "coreschemas/datatypes.xsd");
        NSFILEMAP.put("datatypes-base.xsd", "coreschemas/datatypes-base.xsd");
        NSFILEMAP.put("voc.xsd", "coreschemas/voc.xsd");
        NSFILEMAP.put("NarrativeBlock.xsd", "coreschemas/NarrativeBlock.xsd");
    }

    private static Map<String, LSInput> schemaPool = new HashMap<String, LSInput>();

    public LSInput getSchemaInputStream(String key, LSInput input) {

        if (schemaPool.containsKey(key))
            return schemaPool.get(key);
        else
            return loadDocumentFromStorage(key, input);
    }

    private LSInput loadDocumentFromStorage(String key, LSInput input) {
        String path = NSFILEMAP.get(key);
        InputStream stream = getClass().getClassLoader().getResourceAsStream("resource/" + path);
        if (input != null) {
            input.setCharacterStream(new InputStreamReader(stream));
            schemaPool.put(key, input);
        }
        return input;
    }

    @Override
    public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {
        LSInput input = new DOMInputImpl();
        input.setPublicId(publicId);
        input.setSystemId(systemId);
        input.setBaseURI(baseURI);

        File file = new File(systemId);

        return getSchemaInputStream(file.getName(), input);
    }
}
